package com.ray.friendslist.wall;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;
import android.util.Log;

import com.ray.friendslist.content.task.CommonTask;
import com.ray.friendslist.content.task.ParamCallback;
import com.ray.friendslist.http.HttpManager;

public class WallItemsArray extends CommonTask<List<JSONObject>> {

	private List<JSONObject> mWallItemsList;

	public WallItemsArray(ParamCallback<List<JSONObject>> paramCallback) {
		super(paramCallback);
		mWallItemsList = new ArrayList<JSONObject>();
	}

	@Override
	public List<JSONObject> convert(String s) throws Exception {
		try {
			JSONObject jsonObject = new JSONObject(HttpManager.getInstance()
					.loadAsString(s));
			jsonObject = jsonObject.getJSONObject("response");
//			Log.i("ray", "Wall JSONArray  " + jsonObject.toString());
			JSONArray itemsJsonArray = jsonObject.getJSONArray("wall");
			JSONArray profilesJsonArray = jsonObject.getJSONArray("profiles");
			JSONArray groupsJsonArray = jsonObject.getJSONArray("groups");
			if (itemsJsonArray.length() == 0 || profilesJsonArray.length() == 0) {
				return null;
			}
			return editJsonArray(profilesJsonArray, itemsJsonArray,
					groupsJsonArray);
		} catch (JSONException e) {
			Log.e("ray", "FEEDS LOAD ERROR  " + e.getMessage());
			return null;
		}
	}

	private List<JSONObject> editJsonArray(JSONArray profilesJsonArray,
			JSONArray itemsJsonArray, JSONArray groupsJsonArray)
			throws JSONException {
		boolean compared = false;
		for (int i = 1; i < itemsJsonArray.length(); i++) {
			for (int j = 0; j < profilesJsonArray.length(); j++) {
				if (TextUtils.equals(profilesJsonArray.getJSONObject(j)
						.getString("uid"), itemsJsonArray.getJSONObject(i)
						.getString("from_id"))) {
					mWallItemsList.add(join(profilesJsonArray.getJSONObject(j),
							itemsJsonArray.getJSONObject(i)));
					compared=true;
				}
			}
			if(compared==false){
				for (int j = 0; j < groupsJsonArray.length(); j++) {
					if (TextUtils.equals("-" + groupsJsonArray.getJSONObject(j)
							.getString("gid"), itemsJsonArray.getJSONObject(i)
							.getString("from_id"))) {
						Log.i("ray","WALL FROM GROUP");
						mWallItemsList.add(join(groupsJsonArray.getJSONObject(j),
								itemsJsonArray.getJSONObject(i)));
					}
				}	
			}
			compared=false;
		}
		return mWallItemsList;
	}

	public static JSONObject join(JSONObject profile, JSONObject items) {
		try {
			StringBuilder sb = new StringBuilder();
			sb.append(items.toString());
			sb.deleteCharAt(sb.length() - 1);
			sb.append("," + profile.toString().substring(1));
			Log.i("ray", "EDITED JSON IS ---- " + sb.toString());
			return new JSONObject(sb.toString());
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}

}
